package com.tuerks.sbahn;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class WidgetConfiguration extends Activity {
	public static final String PREFS_NAME = "WidgetPrefs";
	public static final String PREFS_UPDATE_RATE_FIELD_PATTERN = "UpdateRate-%d";
	public static final String PREFS_UPDATE_STATION_FIELD_PATTERN = "Station-%d";
	private static final int PREFS_UPDATE_RATE_DEFAULT = 60;
	private static final String PREFS_UPDATE_STATION_DEFAULT = "";

	private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// get any data we were launched with
		Intent launchIntent = getIntent();
		Bundle extras = launchIntent.getExtras();
		if (extras != null) {
			appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);

			Intent cancelResultValue = new Intent();
			cancelResultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
					appWidgetId);
			setResult(RESULT_CANCELED, cancelResultValue);
		} else {
			// only launch if it's for configuration
			// Note: when you launch for debugging, this does prevent this
			// activity from running. We could also turn off the intent
			// filtering for main activity.
			// But, to debug this activity, we can also just comment the
			// following line out.
			finish();
		}

		setContentView(R.layout.widgetconfiguration);

		final SharedPreferences config = getSharedPreferences(PREFS_NAME, 0);
		final EditText updateRateEntry = (EditText) findViewById(R.id.update_rate_entry);
		final String updateStationEntry = null;
		final Spinner stationSpinner = (Spinner) findViewById(R.id.spinner1);

		final SharedPreferences myPrefs = getSharedPreferences("myPrefs",
				MODE_WORLD_READABLE);
		final String stations = myPrefs.getString("stations", null);

		try {
			if (stations != null) {
				JSONObject jO = new JSONObject(stations);
				JSONArray jA = jO.getJSONArray("stations");
				List<String> list = new ArrayList<String>();
				for (int i = 0; i < jA.length(); i++) {
					list.add(jA.getString(i));
				}
				final String[] sA = new String[jA.length()];
				final String[] sAdecoded = new String[jA.length()];
				list.toArray(sA);
				for (int i = 0; i < sA.length; i++) {
					sAdecoded[i] = URLDecoder.decode(sA[i]);
					sAdecoded[i] = sAdecoded[i].substring(0,
							sAdecoded[i].indexOf("#"));
				}

				ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
						this, android.R.layout.simple_spinner_dropdown_item,
						sAdecoded);
				stationSpinner.setAdapter(spinnerArrayAdapter);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		updateRateEntry.setText(String.valueOf(config.getInt(
				String.format(PREFS_UPDATE_RATE_FIELD_PATTERN, appWidgetId),
				PREFS_UPDATE_RATE_DEFAULT)));
		// updateStationEntry.setText(String.valueOf(config.getString(String.format(PREFS_UPDATE_STATION_FIELD_PATTERN,
		// appWidgetId), PREFS_UPDATE_STATION_DEFAULT)));

		Button saveButton = (Button) findViewById(R.id.save_button);

		saveButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				int updateRateSeconds = Integer.parseInt(updateRateEntry
						.getText().toString());
				final String stations = myPrefs.getString("stations", null);
				String[] sA = null;

				try {
					if (stations != null) {
						JSONObject jO = new JSONObject(stations);
						JSONArray jA = jO.getJSONArray("stations");
						List<String> list = new ArrayList<String>();
						for (int i = 0; i < jA.length(); i++) {
							list.add(jA.getString(i));
						}
						sA = new String[jA.length()];
						final String[] sAdecoded = new String[jA.length()];
						list.toArray(sA);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String updateStation = sA[(int) stationSpinner
						.getSelectedItemId()];
				Log.v("s-bahn", updateStation);

				// store off the user setting for update timing
				SharedPreferences.Editor configEditor = config.edit();

				configEditor.putInt(String.format(
						PREFS_UPDATE_RATE_FIELD_PATTERN, appWidgetId),
						updateRateSeconds);
				configEditor.putString(String.format(
						PREFS_UPDATE_STATION_FIELD_PATTERN, appWidgetId),
						updateStation);
				configEditor.commit();

				if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {

					// tell the app widget manager that we're now configured
					Intent resultValue = new Intent();
					resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
							appWidgetId);
					setResult(RESULT_OK, resultValue);

					Intent widgetUpdate = new Intent();
					widgetUpdate
							.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
					widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
							new int[] { appWidgetId });

					// make this pending intent unique
					widgetUpdate.setData(Uri.withAppendedPath(
							Uri.parse(WidgetProvider.URI_SCHEME
									+ "://widget/id/"),
							String.valueOf(appWidgetId)));
					PendingIntent newPending = PendingIntent.getBroadcast(
							getApplicationContext(), 0, widgetUpdate,
							PendingIntent.FLAG_UPDATE_CURRENT);

					// schedule the new widget for updating
					AlarmManager alarms = (AlarmManager) getApplicationContext()
							.getSystemService(Context.ALARM_SERVICE);
					alarms.setRepeating(AlarmManager.ELAPSED_REALTIME,
							SystemClock.elapsedRealtime(),
							updateRateSeconds * 1000, newPending);
				}

				// activity is now done
				finish();
			}
		});
	}
}